package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
import java.nio.file.Paths;

@WebServlet(name = "SubmitArticleServlet", urlPatterns = "/submit-article")
@MultipartConfig
public class SubmitArticleServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String title = req.getParameter("title");
        String type = req.getParameter("type");
        String content = req.getParameter("content");
        Part imagePart = req.getPart("image");
        String imageUrl = null;
        if (imagePart != null && imagePart.getSize() > 0) {
            String fileName = Paths.get(imagePart.getSubmittedFileName()).getFileName().toString();
            String uploadDir = getServletContext().getRealPath("/uploads");
            java.io.File dir = new java.io.File(uploadDir);
            if (!dir.exists()) dir.mkdirs();
            String filePath = uploadDir + java.io.File.separator + fileName;
            imagePart.write(filePath);
            imageUrl = "uploads/" + fileName;
            // 在内容末尾插入图片
            content = content + "<br/><img src='" + imageUrl + "' style='max-width:100%;'/>";
        }
        HttpSession session = req.getSession(false);
        String author = session != null && session.getAttribute("username") != null ? (String) session.getAttribute("username") : "匿名用户";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                     "INSERT INTO articles(title, type, content, author, create_time) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, title);
            ps.setString(2, type);
            ps.setString(3, content);
            ps.setString(4, author);
            ps.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
            ps.executeUpdate();
            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    int id = rs.getInt(1);
                    resp.sendRedirect("article-detail?id=" + id);
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.sendRedirect("submit-article.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("submit-article.jsp");
    }
} 